<template>
  <div class="wrapper">
    <!-- 添加分类的 dialog 组件 -->
    <el-dialog v-model="visible" title="添加分类">
      <el-form :model="form">
        <el-form-item label="分类名称">
          <el-input v-model="categoryName" autofocus></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="addCategory">确认添加</el-button>
      </span>
      </template>
    </el-dialog>
    <el-layout>
      <el-aside width="200px">
        <el-menu default-active="1" :default-openeds="['1']" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
          <el-submenu index="1">
              <span>所有分类</span>
            <el-menu-item v-for="(item, index) in categories" :key="index" :index="index+1" @click="handleCategoryClick(item)">
              {{item.CategoryName}}
            </el-menu-item>
          </el-submenu>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header style="background-color: #f9fafc;">
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确定删除?"
            @confirm="confirmEvent"
            @cancel="cancelEvent"
            >
            <template #reference>
              <el-button type="danger">删除分类</el-button>
            </template>
          </el-popconfirm>
          <!-- <el-button type="danger" icon="el-icon-delete" @click="handleDeleteCategory">删除分类</el-button> -->
          <el-button type="primary" @click="visible = true">添加分类</el-button>
        </el-header>
        <el-main>
          <el-table 
            :data="tableData" 
            style="width: 100%" 
            table-layout="auto"
            lazy
            empty-text="这个分类下还没有文章呢 ！">
            <!-- <el-table-column prop="id" label="编号" width="100" /> -->

            <el-table-column prop="title" label="标题" />
            <el-table-column prop="articleExcerpt" label="主要内容"/>
            <el-table-column prop="articleTags" label="标签"/>
            <el-table-column prop="articleCategory" label="分类"/>
            <el-table-column prop="articleCategoryStatus" label="文章状态" />
            <el-table-column prop="articleUpdated" label="上次修改时间" />
            
            <el-table-column fixed="right" label="操作" >
              <template #default="{row}">
                <el-button type="primary" size="small" @click="handleClick(row.id)">详情</el-button>
                <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-layout>
  </div>
</template>

<script setup>
import axios from 'axios'
import VueCookies from 'vue-cookies'
import { onMounted } from 'vue';
import { getCurrentInstance, ref } from 'vue';
import { useRouter } from 'vue-router';
import { InfoFilled } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance();
const tableData = ref([]);
const categories = ref([]);
let selectedCategory = "";

// 添加分类 dialog 相关变量
const visible = ref(false);
const categoryName = ref('');
const form = ref({});

const loginInfo = VueCookies.get("loginInfo");
const account = loginInfo ? loginInfo.account : null; // 如果 loginInfo 存在，则从中取出 account 字段，否则返回 null

const router = useRouter();

const confirmEvent = async() => {
  const data = {
    userAccount: account,
    category: selectedCategory.id
  };
  const num = tableData._rawValue.length;
  console.log(tableData._rawValue.length);
  if(num != 0)
  {
    proxy.$message.error('该分类还有文章, 无法删除该分类');
    return;
  }
  const url = 'http://localhost:8081/api/deleteCategory'
    
  try{
    const res = await axios.post(url, data);

    if(res.data.code === 2000)
    {
      getCategories();
      proxy.$message.success("删除成功");

    }else{
      proxy.$message.error(res.data.message);
    }
  }catch(e){
    proxy.$message.error("删除失败");
  }
}

const cancelEvent = () => {

}

const getCategories = async() =>{
  try{
    const data = {
      userAccount: account,
    };

    const url = 'http://localhost:8081/api/getAllArticleCategory'

    const res = await axios.post(url, data);

    if (res.data.code === 2000) {
      categories.value = res.data.tableData;
      selectedCategory = categories.value[0];
      getTableData(selectedCategory);
    }else {
      proxy.$message.error(res.data.message);
      categories.value = [];
      selectedCategory = "";
      tableData.value = [];
    }
  } catch(e){
    proxy.$message.error('获取文章分类失败');
  }
}

const getTableData = async(category) =>{
  const url = 'http://localhost:8081/api/publishArticle';
  try{
    const data = {
      userAccount: account,
      category: category.id
    };

    //console.log(data.category);

    const res = await axios.post(url, data);

    if (res.data.code === 2000) {
      tableData.value = res.data.tableData;
    }else {
      proxy.$message.error(res.data.message);
      tableData.value = [];
    }
  } catch(e){
    console.log(e);
    proxy.$message.error('文章获取失败');
  }
}

const handleClick = (id) => {
  console.log('click', id)
  setTimeout(() => {
    router.push({
        path : '/deta',
        query: { id: id }
    });
  }, 1000);
}

const handleCategoryClick = (category) => {
  selectedCategory = category;
  getTableData(selectedCategory);
}

// 确认添加分类按钮的点击事件
const addCategory = () => {
  if (!categoryName.value) {
    proxy.$message.warning('分类名称不能为空！');
    return;
  }

  const data = {
    userAccount: account,
    categoryName: categoryName.value
  };

  axios.post('http://localhost:8081/api/addCategory', data)
    .then(response => {
      if (response.data.code === 2000) {
        getCategories();
        proxy.$message.success('添加分类成功');
        visible.value = false;
        categoryName.value = '';
      } else {
        proxy.$message.error(response.data.message);
      }
    })
    .catch(error => {
      console.log(error);
      proxy.$message.error('添加分类失败');
    });
}

// const handleDeleteCategory = () => {
//   if (selectedCategory === "") {
//     proxy.$message.warning("请先选择一个分类");
//   } else {
    
//     }
//   }


const handleDelete = (id) =>{
  try{
    const data = {
      userAccount: account,
      articleId: id
    };

    console.log(data.articleId);

    axios.post('http://localhost:8081/api/deleteArticle', data)
      .then(response => {
        if (response.data.code === 2000) {
          // TODO: 处理删除成功的情况
          getTableData(selectedCategory);
          proxy.$message.success('删除成功');
        } else {
          proxy.$message.error(response.data.message);
        }
      })
      .catch(error => {
        proxy.$message.error('删除文章失败');
      });

  }catch(e){
    proxy.$message.error('删除文章失败');
  }
}

const handleBack = () => {
  router.push({
      path : '/cL'
    });
}

getCategories();

</script>

<style scoped>
.wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.el-menu {
  border-right: 0;
}

.el-submenu__title {
  font-size: 16px;
}
</style>
